package com.lms;

import com.lms.realm.LmsRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfiguration {
    @Bean
    public LmsRealm getRealm(){
        return new LmsRealm();
    }

    @Bean//管理器
    public SecurityManager securityManager(LmsRealm lmsRealm){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager(lmsRealm);
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean=new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //设置拦截规则
        shiroFilterFactoryBean.setLoginUrl("/tologin");
        Map<String, String> filterMap=new HashMap<>();
        filterMap.put("/tologin","anon");//不拦截,开头少加了/
        filterMap.put("/login","anon");//不拦截
        filterMap.put("/css/**","anon");//不拦截
        filterMap.put("/lib/**","anon");//不拦截
        filterMap.put("/**","authc");//拦截
       /* filterMap.put("/admin/**","authc");//拦截admin下面所有的请求
        filterMap.put("/book/admin/**","authc");
        filterMap.put("/rentRecord/admin/**","authc");
        filterMap.put("/returnRecord/admin/**","authc");
        filterMap.put("/role/admin/**","authc");
        filterMap.put("/type/admin/**","authc");
        filterMap.put("/user/admin/**","authc");*/
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }
    @Bean
    @ConditionalOnMissingBean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
        defaultAAP.setProxyTargetClass(true);
        return defaultAAP;
    }

    @Bean//开启注解扫描
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor=new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}
